package cn.xy.controller;

import cn.xy.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

//@Controller
//使用了找个注解,这个controller只会返回字符串,不会走视图解析器
//也可以使用@Controller + @RequestBody
@RestController
@RequestMapping("/json")
public class JsonController {

    @RequestMapping("/j1")
    public String test1() throws JsonProcessingException {
        //创建对象
        User user = new User("恣意",3,"男");

        //创建将java对象转换为json字符串的工具
        ObjectMapper objectMapper = new ObjectMapper();

        //转换为json字符串
        String str = objectMapper.writeValueAsString(user);

        return str;
    }


    @RequestMapping("/j2")
    public String test2() throws JsonProcessingException {
        //创建对象
        User user1 = new User("恣意",3,"男");
        User user2 = new User("心意",3,"男");
        User user3 = new User("小意子",3,"男");

        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3 );

        return new ObjectMapper().writeValueAsString(userList);
    }
}
